﻿using JESAI.DynamicWebApi.Helpers;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace JESAI.DynamicWebApi.Attributes
{
    /// <summary>
    /// 动态接口特性
    /// </summary>
    [Serializable]
    [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Method)]
    public class DynamicWebApiAttribute:Attribute
    {
        /// <summary>
        /// 是否启用，默认：True
        /// </summary>
        public bool IsEnabled { get; set; }

        /// <summary>
        /// 默认：True
        /// </summary>
        public bool IsMetadataEnabled { get; set; }

        public DynamicWebApiAttribute(bool isEnabled = true)
        {
            IsEnabled = isEnabled;
            IsMetadataEnabled = true;
        }

        public virtual bool IsEnabledFor(Type type)
        {
            return IsEnabled;
        }

        public virtual bool IsEnabledFor(MethodInfo method)
        {
            return IsEnabled;
        }

        public virtual bool IsMetadataEnabledFor(Type type)
        {
            return IsMetadataEnabled;
        }

        public virtual bool IsMetadataEnabledFor(MethodInfo method)
        {
            return IsMetadataEnabled;
        }

        public static bool IsExplicitlyEnabledFor(Type type)
        {
            var dynamicWebApiAttr = type.GetTypeInfo().GetSingleAttributeOrNull<DynamicWebApiAttribute>();
            return dynamicWebApiAttr != null && dynamicWebApiAttr.IsEnabledFor(type);
        }

        public static bool IsExplicitlyDisabledFor(Type type)
        {
            var dynamicWebApiAttr = type.GetTypeInfo().GetSingleAttributeOrNull<DynamicWebApiAttribute>();
            return dynamicWebApiAttr != null && !dynamicWebApiAttr.IsEnabledFor(type);
        }

        public static bool IsMetadataExplicitlyEnabledFor(Type type)
        {
            var dynamicWebApiAttr = type.GetTypeInfo().GetSingleAttributeOrNull<DynamicWebApiAttribute>();
            return dynamicWebApiAttr != null && dynamicWebApiAttr.IsMetadataEnabledFor(type);
        }

        public static bool IsMetadataExplicitlyDisabledFor(Type type)
        {
            var dynamicWebApiAttr = type.GetTypeInfo().GetSingleAttributeOrNull<DynamicWebApiAttribute>();
            return dynamicWebApiAttr != null && !dynamicWebApiAttr.IsMetadataEnabledFor(type);
        }

        public static bool IsMetadataExplicitlyDisabledFor(MethodInfo method)
        {
            var dynamicWebApiAttr = method.GetSingleAttributeOrNull<DynamicWebApiAttribute>();
            return dynamicWebApiAttr != null && !dynamicWebApiAttr.IsMetadataEnabledFor(method);
        }

        public static bool IsMetadataExplicitlyEnabledFor(MethodInfo method)
        {
            var dynamicWebApiAttr = method.GetSingleAttributeOrNull<DynamicWebApiAttribute>();
            return dynamicWebApiAttr != null && dynamicWebApiAttr.IsMetadataEnabledFor(method);
        }
    }
}